const St = imports.gi.St;
const Lang = imports.lang;
const PanelMenu = imports.ui.panelMenu;
//const PopupMenu = imports.ui.popupMenu;
const Main = imports.ui.main;
const Mainloop = imports.mainloop;
const Clutter = imports.gi.Clutter;

const UPDATE_INTERVAL = 300; // update interval is 5 minutes
const DESATURATE = true; // adpat to gnome-shell style

const BeijingAirEx = imports.ui.extensionSystem.extensions["BeijingAir@binli.opensuse.org"];
const PM25 = BeijingAirEx.pm25.PM25;
const PM25Indicator = BeijingAirEx.indicator.PM25Indicator;

function BeijingAir(extensionMeta) {
	this._init.apply(this, [extensionMeta, ]);
}

BeijingAir.prototype = {
	__proto__: PanelMenu.Button.prototype,

	run: false,
	pm25: null,
	indicator: null,

	_init: function(extensionMeta) {
		log ('BeijingAir _init');
		PanelMenu.Button.prototype._init.call(this, 0);
		this.extensionMeta = extensionMeta;
		this.pm25 = new PM25();
		this.indicator = new PM25Indicator(this.extensionMeta, this.pm25);
		this.build_ui();
		log ("BeijingAir _init end.");
	},

	update: function() {
		this.indicator.update();
		return this.run;
	},

	build_ui: function() {
		log ("BeijingAir build_ui");
		this.box = new St.BoxLayout();

		if (DESATURATE)
		 	this.box.add_effect_with_name("grayscale", new Clutter.DesaturateEffect({ factor: 1 }));

		this.box.add_actor(this.indicator.actor);
		this.menu.addMenuItem(this.indicator.menu);

		this.actor.add_actor(this.box);
	},

	enable: function() {
		log ("BeijingAir enable");
		this.run = true;
		this.update();
		this._update_handler = Mainloop.timeout_add_seconds(UPDATE_INTERVAL, Lang.bind(this, this.update));
		Main.panel._rightBox.insert_actor(this.actor, 0);
		Main.panel._menus.addMenu(this.menu);
	},

	disable: function() {
		log ("BeijingAir disable");
		this.run = false;
		Mainloop.source_remove(this._update_handler);
		Main.panel._rightBox.remove_actor(this.actor);
		Main.panel._menus.removeMenu(this.menu)
	}
}

function init(extensionMeta) {
	return new BeijingAir(extensionMeta);
}

